package system

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type Site_messageApi struct{}

var wsClients = make(map[*websocket.Conn]bool)
var wsBroadcast = make(chan *system.Site_message, 100)
var wsPushStarted = false

// CreateSite_message 创建站内信
// @Tags Site_message
// @Summary 创建站内信
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Site_message true "创建站内信"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /site_message/createSite_message [post]
func (site_messageApi *Site_messageApi) CreateSite_message(c *gin.Context) {
	ctx := c.Request.Context()
	var site_message system.Site_message
	err := c.ShouldBindJSON(&site_message)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = site_messageService.CreateSite_message(ctx, &site_message)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}
	// 新消息推送到WebSocket
	if wsBroadcast != nil {
		wsBroadcast <- &site_message
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteSite_message 删除站内信
// @Tags Site_message
// @Summary 删除站内信
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Site_message true "删除站内信"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /site_message/deleteSite_message [delete]
func (site_messageApi *Site_messageApi) DeleteSite_message(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	ID := c.Query("ID")
	err := site_messageService.DeleteSite_message(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteSite_messageByIds 批量删除站内信
// @Tags Site_message
// @Summary 批量删除站内信
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
// @Router /site_message/deleteSite_messageByIds [delete]
func (site_messageApi *Site_messageApi) DeleteSite_messageByIds(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	IDs := c.QueryArray("IDs[]")
	err := site_messageService.DeleteSite_messageByIds(ctx, IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateSite_message 更新站内信
// @Tags Site_message
// @Summary 更新站内信
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Site_message true "更新站内信"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /site_message/updateSite_message [put]
func (site_messageApi *Site_messageApi) UpdateSite_message(c *gin.Context) {
	// 从ctx获取标准context进行业务行为
	ctx := c.Request.Context()

	var site_message system.Site_message
	err := c.ShouldBindJSON(&site_message)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = site_messageService.UpdateSite_message(ctx, site_message)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindSite_message 用id查询站内信
// @Tags Site_message
// @Summary 用id查询站内信
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param ID query uint true "用id查询站内信"
// @Success 200 {object} response.Response{data=system.Site_message,msg=string} "查询成功"
// @Router /site_message/findSite_message [get]
func (site_messageApi *Site_messageApi) FindSite_message(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	ID := c.Query("ID")
	resite_message, err := site_messageService.GetSite_message(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(resite_message, c)
}

// GetSite_messageList 分页获取站内信列表
// @Tags Site_message
// @Summary 分页获取站内信列表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "分页获取站内信列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /site_message/getSite_messageList [get]
func (site_messageApi *Site_messageApi) GetSite_messageList(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	var pageInfo systemReq.Site_messageSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := site_messageService.GetSite_messageInfoList(ctx, pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetSite_messagePublic 不需要鉴权的站内信接口
// @Tags Site_message
// @Summary 不需要鉴权的站内信接口
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
// @Router /site_message/getSite_messagePublic [get]
func (site_messageApi *Site_messageApi) GetSite_messagePublic(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	site_messageService.GetSite_messagePublic(ctx)
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的站内信接口信息",
	}, "获取成功", c)
}

// GetUserMessages 分页获取用户消息
// @Tags Site_message
// @Summary 分页获取用户消息
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /site_message/getUserMessages [get]
func (site_messageApi *Site_messageApi) GetUserMessages(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	status := c.DefaultQuery("status", "")
	title := c.DefaultQuery("title", "")

	msgs, total, err := site_messageService.GetAllMessages(page, pageSize, status, title)
	if err != nil {
		response.FailWithMessage("获取消息失败", c)
		return
	}
	response.OkWithDetailed(gin.H{
		"list":     msgs,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	}, "获取成功", c)
}

// MarkMessageRead 标记消息为已读
// @Tags Site_message
// @Summary 标记消息为已读
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body object true "消息ID"
// @Success 200 {object} response.Response{msg=string} "成功"
// @Router /site_message/markMessageRead [post]
func (site_messageApi *Site_messageApi) MarkMessageRead(c *gin.Context) {
	var req struct {
		ID uint64 `json:"id"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}
	err := site_messageService.MarkMessageRead(req.ID)
	if err != nil {
		response.FailWithMessage("标记已读失败", c)
		return
	}
	response.OkWithMessage("标记已读成功", c)
}

// BatchMarkRead 批量标记为已读
// @Tags Site_message
// @Summary 批量标记为已读
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /site_message/batchMarkRead [POST]
func (site_messageApi *Site_messageApi) BatchMarkRead(c *gin.Context) {
	var req struct {
		Ids []uint64 `json:"ids"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}
	if err := site_messageService.BatchMarkRead(req.Ids); err != nil {
		response.FailWithMessage("标记失败", c)
		return
	}
	response.OkWithMessage("标记成功", c)
}

// BatchDelete 批量删除
// @Tags Site_message
// @Summary 批量删除
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /site_message/batchDelete [POST]
func (site_messageApi *Site_messageApi) BatchDelete(c *gin.Context) {
	var req struct {
		Ids []uint64 `json:"ids"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}
	if err := site_messageService.BatchDelete(req.Ids); err != nil {
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// AllMarkRead 全部标记为已读
// @Tags Site_message
// @Summary 全部标记为已读
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /site_message/allMarkRead [POST]
func (site_messageApi *Site_messageApi) AllMarkRead(c *gin.Context) {
	if err := site_messageService.AllMarkRead(); err != nil {
		response.FailWithMessage("全部已读失败", c)
		return
	}
	response.OkWithMessage("全部已读", c)
}

// AllDelete 全部删除
// @Tags Site_message
// @Summary 全部删除
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.Site_messageSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /site_message/allDelete [POST]
func (site_messageApi *Site_messageApi) AllDelete(c *gin.Context) {
	if err := site_messageService.AllDelete(); err != nil {
		response.FailWithMessage("全部删除失败", c)
		return
	}
	response.OkWithMessage("全部删除", c)
}

// WebSocketHandler WebSocket处理器
// @Tags Site_message
// @Summary WebSocket连接
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=object,msg=string} "连接成功"
// @Router /site_message/ws [get]
func (site_messageApi *Site_messageApi) WebSocketHandler(c *gin.Context) {
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool { return true },
	}
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		global.GVA_LOG.Error("WebSocket升级失败", zap.Error(err))
		return
	}
	defer conn.Close()
	wsClients[conn] = true

	// 启动全局推送协程（只启动一次）
	if !wsPushStarted {
		wsPushStarted = true
		go func() {
			for msg := range wsBroadcast {
				for client := range wsClients {
					_ = client.WriteJSON(gin.H{"type": "new_message", "data": msg})
				}
			}
		}()
	}

	// 保持连接
	for {
		_, _, err := conn.ReadMessage()
		if err != nil {
			delete(wsClients, conn)
			break
		}
	}
}
